const app = getApp();
const util = require('../../utils/util.js');
Page({
  data: {
    topNum: 0,
    showHeader: false,
    filterShow: false,
    select_category: {},
    category_list: [], //种类列表
    goods_list: [], //商品列表
    brand_list: [], //品牌列表
    attr_list: [], //属性列表
    other_list: [], //其它的属性
    brand_fold: '',
    fold_list: [], //折叠数组
    more_fold: '',
    scrollHeight: '',
    scrollHeight2: '',
    refreshData: {
      page: 1,
      size: 10,
      isEnd: false
    }, //分页信息
    cate_id: '', //分类ID
    fcate_id: '', //选择小类别之前的大类别 id
    keyword: '', //关键字
    b_id: '', //品牌id
    filtrate_flag: 0, //热销  价格  筛选
    order: 0, //热销和价格排序
    key: 0, //热销和价格排序
    a_id: '', //其它
    reset_height: false, //第一次进来是搜索结果 没有头部热销等,点击其它的栏目如水果高度要重新设置
    comprehensive_order: false,
    comprehensive_text: '综合排序',
    show_fly_img: false,
    goodsImageFly: '',
    toNextClassFlag: false,
    floorstatus: false,
    topNum: 0,
    globalImageUrl: app.globalData.imageUrl
  },
  /**
   * 计算滚动的可用高度
   */
  computeScrollViewHeight() {
    let that = this;
    let query = wx.createSelectorQuery().in(this);
    query.select('.search_header').boundingClientRect();
    query.select('.child-class_p-hh').boundingClientRect();
    query.select('.class-filtrate-my-p').boundingClientRect();
    query.exec(res => {
      let searchHeight = res[0].height;
      let headerHeight = res[1].height;
      let rankHeight = res[2].height;
      let windowHeight = wx.getSystemInfoSync().windowHeight;
      let scrollHeight = windowHeight - searchHeight;
      let scrollHeight2 = scrollHeight - headerHeight - rankHeight;
      this.setData({
        scrollHeight: scrollHeight,
        scrollHeight2: scrollHeight2
      });
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //请求分享数据
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
      data: {},
      method: 'GET',
      dataType: 'json',
      success: res => {
        if (res.data.code == '200') {
          this.setData({
            share_default_title: res.data.datas.title,
            share_default_image_url: res.data.datas.imageUrl
          })
        }
      }
    })
    util.share();
    if (options.cate_id) {
      this.setData({
        cate_id: options.cate_id,
        fcate_id: options.cate_id,
      })
    }
    if (options.b_id) {
      this.setData({
        b_id: options.b_id,

      })
    }
    if (options.keyword) {
      this.setData({
        keyword: options.keyword
      })
    }
    this.getSearchData(this.data);
    //this.search(this.data);
    wx.getStorage({
      key: 'cart_count',
      success: (res) => {
        this.setData({
          cart_count: res.data
        })
      },
    })
    wx.getStorage({
      key: 'key',
      success: (res) => {
        this.setData({
          member_key: res.data
        })
        this.getCartInfo();
      },
    })
    this.cartPos = {};
    this.cartPos['x'] = app.globalData.sw - 18;
    this.cartPos['y'] = 28;

  },
  onShow: function () {
    var self = this;
    if (!this.data.key) {
      wx.getStorage({
        key: 'key',
        success: (res) => {
          this.setData({
            member_key: res.data
          })
          this.getCartInfo();
        },
      })
    }
    wx.getStorage({
      key: 'cart_count',
      success: (res) => {
        self.setData({
          cart_count: res.data
        })
      },
    })

    if (this.data.member_key) {
      this.getCartInfo();
    }
  },
  //获取搜索的数据
  getSearchData: function (paramData) {
    var self = this;
    if (self.data.refreshData.isEnd) {
      return;
    }
    var str = '';
    if (paramData.keyword) {
      str += '&keyword=' + paramData.keyword;
    }
    if (paramData.cate_id) {
      str += '&cate_id=' + paramData.cate_id;
    }
    if (paramData.b_id) {
      str += '&b_id=' + paramData.b_id;
    }

    if (paramData.a_id) {
      str += '&a_id=' + paramData.a_id;
    }
    if (paramData.key) {
      str += '&key=' + paramData.key;
    }
    if (paramData.order) {
      str += '&order=' + paramData.order;
    }
    if (paramData.cate_id || paramData.b_id) {
      this.setData({
        showHeader: true
      });
      if (self.data.reset_height) {
        let query = wx.createSelectorQuery().in(this);
        query.select('.child-class_p-hh').boundingClientRect();
        query.exec(res => {
          let myHeight = res[0].height;
          let scrollHeight2 = self.data.scrollHeight2 - myHeight;
          this.setData({
            scrollHeight2: scrollHeight2,
            reset_height: false
          });
        });
      }
    }
    if (!paramData.keyword) {
      wx.getStorage({
        key: 'class_goods_list' + str + '&curpage=' + self.data.refreshData.page + '&page=' + self.data.refreshData.size,
        success: (res) => {
          if (Date.parse(new Date()) - res.data.cachTime > app.globalData.cachTempTime) {
            self.getRequest(str);
          } else {
            self.show_datas(res.data);
          }
        },
        fail: () => {
          //获取列表数据
          self.getRequest(str);
        }
      })
    } else {
      wx.getStorage({
        key: 'search_his_list',
        success: (res) => {
          if (res.data.indexOf(paramData.keyword) == -1) {
            res.data.unshift(paramData.keyword)
            if (res.data.length > 21) {
              res.data.pop();
            }
            wx.setStorage({
              key: 'search_his_list',
              data: res.data
            })
          }

        },
        fail: () => {
          wx.setStorage({
            key: 'search_his_list',
            data: [paramData.keyword]
          })
        }
      })
      self.getRequest(str);
    }



  },
  getRequest: function (str) {
    var self = this;
    if (self.data.refreshData.page == 1) {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=goods&op=class_goods_list' + str + '&curpage=' + self.data.refreshData.page + '&page=' + self.data.refreshData.size,
      success(res) {
        if (str.indexOf("keyword") == -1) {
          res.data.cachTime = Date.parse(new Date());
          wx.setStorage({
            key: 'class_goods_list' + str + '&curpage=' + self.data.refreshData.page + '&page=' + self.data.refreshData.size,
            data: res.data
          })
        }

        self.show_datas(res.data);
      },
      fail: function () {
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        })
      },
      complete: function () {
        if (self.data.refreshData.page == 1) {
          wx.hideLoading()
        }
      }
    });
  },
  show_datas: function (data) {
    var self = this;
    if (self.data.refreshData.page == 1) {
      //初始化折叠数组 
      if (data.datas.attr_array) {
        self.data.fold_list = new Array(data.datas.attr_array.length);
      }
      self.setData({
        category_list: data.datas.left_class, //获取数据数组 
        brand_list: data.datas.brand_array,
        attr_list: data.datas.attr_array,
        other_list: data.datas.more_class
      });
      for (let i = 0; i < data.datas.left_class.length; i++) {
        if (data.datas.left_class[i].selected && i != (data.datas.left_class.length - 1)) {
          self.setData({
            next_gc_id: data.datas.left_class[i + 1].gc_id,
            curClassIndex: i
          })
        }
      }
    }
    let tempData = [];
    //如果是第一页数据只添加新的数据 
    self.data.refreshData.page > 1 ? tempData = self.data.goods_list.concat(data.datas.goods_list) : tempData = data.datas.goods_list;
    self.setData({
      goods_list: tempData, //获取数据数组  
    });

    if (!data.hasmore) {
      self.data.refreshData.isEnd = true; //把“没有数据”设为true，显示  
      self.setData({
        refreshData: self.data.refreshData
      });
    }
  },
  /**
   * 获取商品列表
   */
  get_goods_list: function (event) {
    var selected = event.currentTarget.dataset.selected;
    if (selected == 1) {
      return false;
    }
    var self = this;
    self.setData({
      topNum: 0
    });
    self.data.refreshData.page = 1;
    self.data.cate_id = event.currentTarget.dataset.gcid;
    self.data.fcate_id = event.currentTarget.dataset.gcid;
    var curCateIndex = event.currentTarget.dataset.id;
    if (self.data.keyword && self.data.cate_id) {
      self.data.reset_height = true;
    }
    self.data.refreshData.isEnd = false;
    self.data.keyword = '';
    self.data.key = 0;
    self.data.order = 0;
    self.data.a_id = '';
    self.data.b_id = 0;
    self.setData({
      filtrate_flag: 0,
      refreshData: self.data.refreshData
    });
    if (!curCateIndex && curCateIndex != 0) {
      if (this.data.curClassIndex == this.data.category_list.length - 1) {
        curCateIndex = 0
      } else {
        curCateIndex = this.data.curClassIndex + 1
      }
    }
    if (curCateIndex <= 4) {
      self.setData({
        curCateIndex: 'curCate0'
      });
    } else {
      self.setData({
        curCateIndex: 'curCate' + (curCateIndex - 5)
      });
    }
    this.getSearchData(this.data);
  },
  //筛选商品
  filtrate_goods: function (event) {
    var self = this;
    var filtrate_type = event.currentTarget.dataset.ftype; //1热销 2价格由低到高 3价格由高到低 4筛选
    self.data.refreshData.page = 1;
    self.data.refreshData.isEnd = false;
    self.setData({
      refreshData: self.data.refreshData,
      filtrate_flag: filtrate_type
    });
    switch (filtrate_type) {
      case '1':
        self.data.key = 1;
        self.data.order = 2;
        break;
      //2价格由低到高
      case '2':
        self.data.key = 3;
        self.data.order = 1;
        break;
      //3价格由高到低
      case '3':
        self.data.key = 3;
        self.data.order = 2;
        break;
      //筛选
      case '4':
        self.setData({
          filterShow: true
        });
        break;
    }
    this.getSearchData(this.data);
  },
  /**
   * 品牌选择
   */
  brandSel: function (event) {
    var self = this;
    var bid = event.currentTarget.dataset.bid;
    self.data.refreshData.page = 1;
    self.data.refreshData.isEnd = false;
    self.setData({
      refreshData: self.data.refreshData
    });
    if (bid == self.data.b_id) {
      self.setData({
        b_id: 0
      });
    } else {
      self.setData({
        b_id: bid
      });
    };
    this.getSearchData(this.data);
  },
  /**
   * 属性选择
   */
  attrSel: function (event) {
    var self = this;
    var aid = event.currentTarget.dataset.aid;
    self.data.refreshData.page = 1;
    self.data.refreshData.isEnd = false;
    self.setData({
      refreshData: self.data.refreshData
    });
    if (self.data.a_id.indexOf(aid) != -1) {
      self.setData({
        a_id: self.data.a_id.replace(aid, '')
      });
    } else {
      self.setData({
        a_id: self.data.a_id + aid + '_'
      });
    };
    this.getSearchData(this.data);
  },
  /**
   * 类别选择
   */
  classSel: function (event) {
    var self = this;
    var cid = event.currentTarget.dataset.cid;
    self.data.refreshData.page = 1;
    self.data.refreshData.isEnd = false;
    self.setData({
      refreshData: self.data.refreshData
    });
    if (self.data.cate_id == cid) {
      self.setData({
        cate_id: self.data.fcate_id
      });
    } else {
      self.setData({
        cate_id: cid
      });
    };
    this.getSearchData(this.data);
  },
  //重置
  filterReset: function () {
    let self = this;
    self.data.refreshData.page = 1;
    self.data.refreshData.isEnd = false;
    self.setData({
      a_id: '',
      b_id: '',
      cate_id: self.data.fcate_id,
      refreshData: self.data.refreshData
    });
    self.getSearchData(self.data);
  },
  //完成
  filterComplete: function () {
    let self = this;
    self.setData({
      filterShow: false
    });
  },
  hideFilter: function () {
    let self = this;
    self.setData({
      filterShow: false,
      filtrate_flag: 0
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.computeScrollViewHeight();
  },
  //滚动到底部触发事件  
  searchScrollLower: function (e) {
    let that = this;
    if (!that.data.refreshData.isEnd) {
      that.data.refreshData.page = that.data.refreshData.page + 1;
      that.getSearchData(this.data);
    }
    // 可以加载下一分类
    // setTimeout(function () {
    //   if (that.data.refreshData.isEnd) {
    //     that.setData({
    //       toNextClassFlag: true
    //     })
    //   }
    // }, 1000)

    // if (that.data.refreshData.isEnd) {
    //   //加载下一分类
    //   this.get_goods_list(e)
    // }
  },
  // touchstartEvent: function (e) {
  //   this.setData({
  //     startPointX: e.changedTouches[0].pageX,
  //     startPointY: e.changedTouches[0].pageY
  //   })
  // },
  // touchendEvent: function (e) {
  //   let moveX = e.changedTouches[0].pageX - this.data.startPointX;
  //   let moveY = e.changedTouches[0].pageY - this.data.startPointY;
  //   if (this.data.toNextClassFlag) {
  //     if (Math.abs(moveY) > 159) {
  //       //如果当前为‘全部’
  //       if (this.data.category_list[this.data.curClassIndex].child[0].selected) {
  //         //加载下一分类
  //         this.get_goods_list(e)
  //       }
  //     }
  //   }
  // },
  /**
   * 店铺详情页
   */
  toShopDetail: function (event) {
    var goodsId = event.currentTarget.dataset.gid;
    wx.navigateTo({
      url: '../goods_detail/goods_detail?goods_id=' + goodsId
    })
  },
  /**
   * 店铺页面
   */
  toShop: function (event) {
    var shopId = event.currentTarget.dataset.sid;
    wx.navigateTo({
      url: '../store/store?store_id=' + shopId
    });
  },
  /**
   * 添加到购物车
   */
  addCart: function (e) {
    if (!this.data.member_key) {
      if (app.globalData.authorized) {
        wx.navigateTo({
          url: "../chooselogin/chooselogin"
        })
      } else {
        wx.navigateTo({
          url: "../login/login"
        })
      }
      return;
    }
    let self = this;
    let goods_id = e.currentTarget.dataset['goods_id'];
    let quantity = 1;
    let addQuantity = 0;
    let goods_img = e.currentTarget.dataset['goods_image'];
    if (this.data.cartGoods[goods_id]) {
      addQuantity = this.data.cartGoods[goods_id].goods_num * 1 + 1;
    } else {
      addQuantity = 1
    }
    this.setData({
      goodsImageFly: goods_img
    })
    wx.getStorage({
      key: 'key',
      success: (res) => {
        wx.request({
          url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_add_edit',
          data: {
            key: res.data,
            goods_id: goods_id,
            quantity: addQuantity
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          dataType: 'json',
          success: (res) => {
            if (res.data.code == 200) {
              wx.getStorage({
                key: 'cart_count',
                success: (res) => {
                  wx.setTabBarBadge({
                    index: 3,
                    text: String(res.data + quantity)
                  })
                  wx.setStorage({
                    key: 'cart_count',
                    data: res.data + quantity
                  })
                  self.setData({
                    cart_count: res.data + quantity
                  })
                },
              })
              self.addcartAnimation(e);
              self.setData({
                cart_count: self.data.cart_count + 1
              })
              if (this.data.cartGoods[goods_id]) {
                self.data.cartGoods[goods_id].goods_num++;
                self.setData({
                  cartGoods: self.data.cartGoods
                })
              } else {
                self.data.cartGoods[goods_id] = {
                  cart_id: res.data.datas,
                  goods_num: 1
                }
                self.setData({
                  cartGoods: self.data.cartGoods
                })
              }

            } else {
              wx.showToast({
                title: res.data.datas.error,
                icon: 'none'
              })
            }
          }
        });
      },
      fail: () => {
        if (app.globalData.authorized) {
          wx.navigateTo({
            url: "../chooselogin/chooselogin"
          })
        } else {
          wx.navigateTo({
            url: "../login/login"
          })
        }
      }
    })
  },
  cutCart: function (e) {
    var self = this;
    var price = e.currentTarget.dataset.price;
    var goods_id = e.currentTarget.dataset.goods_id;
    if (e.currentTarget.dataset.cart_id) {
      var cart_id = e.currentTarget.dataset.cart_id;
    } else {
      var cart_id = this.data.newCartGoods[goods_id];
    }
    if (this.data.cartGoods[goods_id].goods_num != 1) {
      wx.request({
        url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_add_edit',
        data: {
          key: self.data.member_key,
          goods_id: goods_id,
          quantity: self.data.cartGoods[goods_id].goods_num * 1 - 1,
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          this.data.cartGoods[goods_id].goods_num--;
          this.data.cart_count--;
          this.setData({
            cartGoods: this.data.cartGoods,
            cart_count: this.data.cart_count
          })
          wx.getStorage({
            key: 'cart_count',
            success: (res) => {
              wx.setStorage({
                key: 'cart_count',
                data: res.data - 1
              })
            },
          })
        }
      })
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '确定要删除该商品吗？',
        success: res => {
          if (res.confirm) {
            //调用删除接口
            wx.request({
              url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_del',
              data: {
                key: self.data.member_key,
                cart_id: cart_id
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              dataType: 'json',
              success: res => {
                delete this.data.cartGoods[goods_id];
                this.data.cart_count--;
                this.setData({
                  cartGoods: this.data.cartGoods,
                  cart_count: this.data.cart_count
                })
                wx.getStorage({
                  key: 'cart_count',
                  success: (res) => {
                    wx.setStorage({
                      key: 'cart_count',
                      data: res.data - 1
                    })
                  },
                })
              }
            })
          }
        }
      })
    }

  },
  /**
   * 筛选中显示更多
   */
  showMoreDetail: function (event) {
    let self = this;
    var myIndex = event.currentTarget.dataset.index;
    switch (myIndex) {
      //品牌
      case '-1':
        if (self.data.brand_fold) {
          self.data.brand_fold = '';
          self.setData({
            brand_fold: self.data.brand_fold
          });
        } else {
          self.data.brand_fold = 'show';
          self.setData({
            brand_fold: self.data.brand_fold
          });
        }
        break;
      //分类筛选
      case '-2':
        if (self.data.more_fold) {
          self.data.more_fold = '';
          self.setData({
            more_fold: self.data.more_fold
          });
        } else {
          self.data.more_fold = 'show';
          self.setData({
            more_fold: self.data.more_fold
          });
        }
        break;
      default:
        if (self.data.fold_list[myIndex]) {
          self.data.fold_list[myIndex] = '';
          self.setData({
            fold_list: self.data.fold_list
          });
        } else {
          self.data.fold_list[myIndex] = 'show';
          self.setData({
            fold_list: self.data.fold_list
          });
        }
        break;
    }
  },
  comprehensiveOrder: function () {
    this.setData({
      comprehensive_order: !this.data.comprehensive_order
    })
  },
  selectOrder: function (event) {
    var comprehensive = event.currentTarget.dataset.comprehensive ? true : false;
    this.setData({
      comprehensive_order: comprehensive ? this.data.comprehensive_order : !this.data.comprehensive_order,
      key: event.currentTarget.dataset.key,
      order: event.currentTarget.dataset.order,
      comprehensive_text: event.currentTarget.dataset.text
    })
    this.search(this.data);
  },
  getCartInfo: function () {
    var self = this;
    wx.request({
      url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_list',
      data: {
        key: self.data.member_key
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      success: res => {
        if (res.data.code == '200') {
          self.setData({
            cart_list: res.data.datas.cart_list
          })
          var selfGoods = {};
          var arrtemp = new Array();
          for (let i = 0; i < 20; i++) {
            arrtemp[i] = new Object();
          }
          for (let i = 0; i < self.data.cart_list.length; i++) {
            for (let j = 0; j < self.data.cart_list[i].goods.length; j++) {
              selfGoods[self.data.cart_list[i].goods[j].goods_id] = {
                cart_id: self.data.cart_list[i].goods[j].cart_id,
                goods_num: self.data.cart_list[i].goods[j].goods_num
              }
            }
          }
          self.setData({
            cartGoods: selfGoods
          })
        }
      }
    })
  },
  addcartAnimation: function (e) {
    if (this.data.show_fly_img)
      return;
    this.finger = {};
    var topPoint = {};
    this.finger['x'] = e.touches["0"].clientX - 200;
    this.finger['y'] = e.touches["0"].clientY + 40;
    if (this.finger['x'] - this.cartPos['x'] < 0) {
      topPoint['x'] = (this.cartPos['x'] - this.finger['x']) / 2 + this.finger['x'];
    } else {
      topPoint['x'] = Math.abs(this.cartPos['x'] - this.finger['x']) / 2 + this.cartPos['x'];
    }
    if (this.finger['y'] < this.cartPos['y']) {
      topPoint['y'] = this.finger['y'] - 80;
    } else {
      topPoint['y'] = this.finger['y'] + 89;
    }
    this.linePos = app.bezier([this.finger, topPoint, this.cartPos], 20);
    this.startAnimation();
  },
  startAnimation: function () {
    var index = 0,
      self = this,
      bezier_points = this.linePos['bezier_points'];
    this.setData({
      show_fly_img: true,
      fly_x: self.finger['x'],
      fly_y: self.finger['y']
    })
    this.timer = setInterval(() => {
      self.setData({
        fly_x: bezier_points[index]['x'],
        fly_y: bezier_points[index]['y']
      })
      index++;
      if (index >= 20) {
        clearInterval(self.timer);
        self.setData({
          show_fly_img: false
        })
      }
    }, 16);
  },
  viewScroll: function (e) {
    if (e.detail.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //回到顶部
  toTop: function (e) { // 一键回到顶部
    this.setData({
      topNum: 0
    });
  },
  onShareAppMessage: function () {
    let share_key = this.data.key ? this.data.key : '';
    let share_path = '';
    if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
      share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
    } else {
      share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
    }
    return {
      title: this.data.share_default_title,
      imageUrl: this.data.share_default_image_url,
      path: share_path
    }
  }

})